Skip to main content

Operator Magic Methods

In Python, methods starting and ending with double underscores '__' are called Magic methods or Dunder methods (Double Under). These methods are widely used for operator overloading. [1]

Operator Overloading

Here is the table of the most common operator megic methods in Python (self and x refer to the same object):

Method DefinitionOperatorDescription
__add__(self, y)x + yThe addition of two objects. The type of x determines which add operator is called.
__contains__(self, y)y in xWhen x is a collection you can test to see if y is in it.
__call__(self, x, y)object(x, y)The class instance (object )will behave like a function which can be called.
__eq__(self, y)x == yReturns True or False depending on the values of x and y.
__ge__(self,y)x >= yReturns True or False depending on the values of x and y.
__getitem__(self,y)x[y]Returns the item at the y-th position in x.
__gt__(self,y)x > yReturns True or False depending on the values of x and y.
__hash__(self)hash(x)Returns an integral value for x.
__int__(self)int(x)Returns an integer representation of x.
__iter__(self)for v in xReturns an iterator object for the sequence x.
__le__(self,y)x <= yReturns True or False depending on the values of x and y.
__len__(self)len(x)Returns the size of x where x has some length attribute.
__mod__(self,y)x%yReturns the value of x modulo y. This is the remainder of x/y.
__mul__(self,y)x*yReturns the product of x and y.
__ne__(self,y)x != yReturns True or False depending on the values of x and y.
__neg__(self)-xReturns the unary negation of x.
__repr__(self)repr(x)Returns a string version of x suitable to be evaluated by the eval function.
__setitem__(self,i,y)x[i] = ySets the item at the i-th position in x to y.
__str__(self)str(x)Return a string representation of x suitable for user-level interaction.
__sub__(self,y)x - yThe difference of two objects.

Table 1: Python Operator Magic Methods [2].

References

Changelog

  • Dec 24, 2024: Add __call__ megic method.